<?PHP
class User{
  public $name                = "";
  public $role                = null;
  public $id                  = -1;
  public $email               = "";
  public $createTimestamp     = "";
  public $lastAccessTimestamp = "";

  public function __construct(){
    $this->role = new Role();
    $this->role->load(1);
  }
  
  /**
   *
   * @param string $name
   * @param string $password
   * @return boolean
   */
  public function login($name,$password){
    if($this->checkPassword($password,trim($name))){
      $this->load(trim($name));
      $this->setLastAccess();
      $args = array();
      $args["user"] = $this;
      EventManager::RaiseEvent("user_login", $args);
      return true;
    }
    else{
      return false;
    }
  }
  
  /**
   *
   * @return boolean
   */
  private function setLastAccess(){
	$res = false;
	$id = DataBase::Current()->EscapeString($this->id);
	$this->lastAccessTimestamp = time();
	$res = DataBase::Current()->Execute("UPDATE {'dbprefix'}user SET 
										last_access_timestamp=NOW() 
									WHERE id = '".$id."'");
	return $res;
  }

  /**
   *
   * @param string $password
   * @param string $name
   * @return boolean
   */
  public function checkPassword($password,$name){
    $name = DataBase::Current()->EscapeString(trim($name));
    $count = DataBase::Current()->ReadField("SELECT COUNT(*) FROM {'dbprefix'}user WHERE 
                        name='".$name."' AND password = '".md5($password.Settings::getValue("salt"))."'");
    return $count == 1;
  }
  
  public function logout(){
     $args = array();
     $args["user"] = $this;
     EventManager::RaiseEvent("user_logout", $args);
     session_destroy();
  }
  
  /**
   *
   * @return array 
   */
  public function getAllUser(){
    $res = array();
    $users = DataBase::Current()->ReadRows("SELECT * FROM {'dbprefix'}user ORDER by name");
    foreach($users as $user){
      $newUser = new User();
      $newUser->id   = $user->id;
      $newUser->name = $user->name;
      $newUser->role->load($user->role);
      $newUser->email = $user->email;
      $newUser->created = $user->created;
      $newUser->access = $user->access;
      $res[] = $newUser;
    }
    return $res;
  }

  /**
   *
   * @param string $name 
   */
  public function load($name){
    $name = DataBase::Current()->EscapeString(strtolower(trim($name)));
    $user = DataBase::Current()->ReadRow("SELECT * FROM {'dbprefix'}user WHERE name = '".$name."'");
	if($user){
		$this->id                  = $user->id;
		$this->name                = $user->name;
		$this->role->load($user->role);
		$this->email               = $user->email;
		$this->createTimestamp     = $user->create_timestamp;
		$this->lastAccessTimestamp = $user->last_access_timestamp;
	}
  }

  /**
   *
   * @return boolean
   */
  public function isGuest(){
    return $this->role->ID == 1;
  }

  /**
   *
   * @return boolean
   */
  public function isAdmin(){
    return $this->role->ID == 2;
  }

  /**
   *
   * @return boolean
   */
  public function exists(){
    $name     = DataBase::Current()->EscapeString(strtolower(trim($this->name)));
    return DataBase::Current()->ReadField("SELECT COUNT(*) FROM {'dbprefix'}user WHERE 
                        name='".$name."'") > 0;
  }

  /**
   *
   * @param string $password
   * @return boolean
   */
  public function insert($password){
    $res = false;
    if($this->validate($password)){
      $name     = DataBase::Current()->EscapeString(strtolower(trim($this->name)));
      $role     = DataBase::Current()->EscapeString($this->role);
      $password = DataBase::Current()->EscapeString(/*md5($password)*/md5($password./*md5(*/Settings::getInstance()->get("salt")/*)*/));
      $email 	= DataBase::Current()->EscapeString($this->email);
      $res = DataBase::Current()->Execute("INSERT INTO {'dbprefix'}user (name, password, role, email, create_timestamp) 
									  VALUES ('".$name."','".$password."','".$role."','".$email."',NOW())");
      $args = array();
      $args["user"] = $this;
      EventManager::RaiseEvent("user_inserted", $args);
      Cache::clear("tables","userlist");
    }
    return $res;
  }
  
  /**
   *
   * @param string $password
   * @return boolean
   */
  public function validate($password){
    $res = true;
    if($res) $res = trim($this->name) != "";                         
    if($res) $res = trim($this->role) != "";
    if($res) $res = trim($password) != "";
	if($res) $res = !$this->exists();
    return $res;
  }

  /**
   *
   * @return boolean
   */
  public function delete(){
    $res = false;
    if(!$this->equals(User::Current())){
      $id = DataBase::Current()->EscapeString(strtolower(trim($this->id)));
      $res = DataBase::Current()->Execute("DELETE FROM {'dbprefix'}user WHERE id = '".$id."'");
      Cache::clear("tables","userlist");
      $args = array();
      $args["user"] = $this;
      EventManager::RaiseEvent("user_deleted", $args);
    }
    return $res;
  }

  /**
   *
   * @param User $user
   * @return boolean
   */
  public function equals(User $user){
    return $this->id == $user->id;
  }
  
  /**
   * 
   * @return User
   */
  public static function Current(){
      if(!isset($_SESSION['user'])){
          $_SESSION['user'] = new User();
      }
      return $_SESSION['user'];
  }
}
?>